<template>
  <div class="app-container">
    <el-form :inline="true">
      <template v-if="showSearch">
        <el-form-item :label="$t('startDate')">
          <el-date-picker
            v-model="startDate"
            clearable
            type="datetime"
            :placeholder="$t('startDate')"
            :picker-options="pickerOptions1"
            value-format="timestamp"
          />
        </el-form-item>
        <el-form-item :label="$t('endDate')">
          <el-date-picker
            v-model="endDate"
            clearable
            type="datetime"
            :placeholder="$t('endDate')"
            :picker-options="pickerOptions1"
            value-format="timestamp"
          />
        </el-form-item>
        <el-form-item :label="$t('deviceCore')">
          <el-input v-model="deviceCore" clearable :placeholder="$t('deviceCore')" />
        </el-form-item>
        <el-form-item :label="$t('status')">
          <el-select v-model="status" @change="pageGetDeviceWarn">
            <el-option
              :label="$t('all')"
              :value="null"
            />
            <el-option
              :label="$t('untreated')"
              :value="0"
            />
            <el-option
              :label="$t('misinformation')"
              :value="1"
            />
            <el-option
              :label="$t('processed')"
              :value="2"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="pageGetDeviceWarn">{{ $t('search') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            v-show="mList.length > 0"
            :disabled="!devModel"
            icon="el-icon-delete"
            type="danger"
            @click="mDel"
          >{{ $t('delete') }}</el-button>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button icon="el-icon-search" circle @click="showSearch=!showSearch" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="cardModel ? 'el-icon-tickets' : 'el-icon-folder'" @click="cardModel=!cardModel" />
      </el-form-item>
    </el-form>
    <el-row v-if="cardModel" :gutter="5">
      <el-col v-for="(item,index) in warnList" :key="index" :span="6">
        <el-card class="box-card mb-1" style="min-height: 385px">
          <div>
            <el-tag v-if="item.status == 2" type="success" @click="edit(item)">{{ formatDeviceWarnStatus(item.status) }}</el-tag>
            <el-tag v-else type="danger" @click="edit(item)">{{ formatDeviceWarnStatus(item.status) }}</el-tag>
            <el-tag type="primary" class="text-sm" v-if="item.grade">{{ item.grade }}</el-tag>
            <div style="float: right">
              <i class="el-icon-s-order" @click="listDeviceWarnHistory(item)"></i>
              <i v-if="devModel" @click="del(item)" class="el-icon-circle-close text-red-300"></i>
              <i class="el-icon-arrow-right" @click.stop="gotoDevice(item)"/>
            </div>
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('device') }}:</span>
            <span v-text="item.deviceName"/>
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('target') }}:</span>{{ item.target }}
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('port') }}:</span>{{item.deviceCore}} / {{item.port }}
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('content') }}:</span>{{ item.value + item.logic + item.logicValue }}
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('thisTimeTrigger') }}:</span>{{ item.thisTimeTriggerCount }}
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('historyTrigger') }}:</span>{{ item.historyTriggerCount }}
          </div>
          <div class="text-sm mt-2" v-if="item.remark">
            <span class="mr-1">{{ $t('remark') }}:</span>{{ item.remark }}
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('startDate') }}:</span>{{ formatDate(item.startDate) }}
          </div>
          <div class="text-sm mt-2">
            <span class="mr-1">{{ $t('endDate') }}:</span>{{ formatDate(item.endDate) }}
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-table
      v-else
      ref="multipleTable"
      style="width: 100%"
      :data="warnList"
      @selection-change="handleSelectionChange"
      @row-click="gotoDevice"
    >
      <el-table-column type="selection" width="50" />
<!--      <el-table-column prop="grade" :label="$t('grade')" width="80" />-->
      <el-table-column prop="deviceName" :label="$t('device')+$t('name')" />
      <el-table-column prop="target" :label="$t('target')" />
      <el-table-column
        prop="updateDate"
        :label="$t('message')"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.value }}</span>
          <span>{{ scope.row.logic }}</span>
          <span>{{ scope.row.logicValue }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" :label="$t('remark')"  />
      <el-table-column :label="$t('status')"  width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 2" type="success" @click="edit(scope.row)">{{ formatDeviceWarnStatus(scope.row.status) }}</el-tag>
          <el-tag v-else type="danger" @click="edit(scope.row)">{{ formatDeviceWarnStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column prop="thisTimeTriggerCount" :label="$t('thisTimeTrigger')" width="100"  />-->
<!--      <el-table-column prop="historyTriggerCount" :label="$t('historyTrigger')" width="100"  />-->
      <el-table-column
        prop="updateDate"
        :label="$t('time')"
        width="300"

      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 13px">{{ formatDate(scope.row.startDate) }}</span>
          <span style="margin-left: 13px">{{ formatDate(scope.row.endDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" :label="$t('function')" >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="listDeviceWarnHistory(scope.row)"
          >{{ $t('history') }}
          </el-button>
          <el-button
            v-if="devModel"
            style="color: #f56c6c"
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="$t('status')"
      :visible.sync="dialogTableVisible"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item :label="$t('status')">
          <el-radio v-model="warn.status" :label="0">{{ $t("untreated") }}</el-radio>
          <el-radio v-model="warn.status" :label="1">{{ $t("misinformation") }}</el-radio>
          <el-radio v-model="warn.status" :label="2">{{ $t("processed") }}</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="updateStatus">{{ $t("confirm") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('history')"
      :visible.sync="showHistory"
    >
      <el-table
        style="width: 100%"
        :data="warnHistoryList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          prop="updateDate"
          :label="$t('value')"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.value }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="updateDate"
          :label="$t('time')"
          width="400"

        >
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span style="margin-left: 13px">{{ formatDate(scope.row.createdDate) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {
  formatDate,
  successNotice,
  cancelNotice
} from '@/util/common'
import {
  pageGetDeviceWarn,
  deleteDeviceWarnList,
  deleteDeviceWarn,
  updateDeviceWarn,
  listDeviceWarnHistory
} from '@/api/iot/iotDeviceWarnApi'
import {
  getDeptId,
  getCompanyId, getDevModel
} from '@/util/storage'
import { getPageSize, setPageSize } from '@/util/storage'
export default {
  name: 'DeviceWarn',
  data() {
    return {
      cardModel: true,
      warnHistoryList: [],
      showHistory: false,
      companyId: getCompanyId(),
      showSearch: true,
      warnList: [],
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      status: null,
      warn: {
        warnId: null,
        status: null
      },
      dialogTableVisible: false,
      mList: [],
      deviceName: null,
      deviceCore: null,
      startDate: 0,
      endDate: 0,
      deptId: null,
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      devModel: getDevModel() === 'true'
    }
  },
  created() {
    const param = this.$route.query
    if (param != null) {
      this.deviceCore = param.deviceCore
      this.deviceName = param.deviceName
      if (this.deviceName) {
        this.setTagsViewTitle()
      }
      if (param.companyId) {
        this.companyId = parseInt(param.companyId)
      }
      if (param.isDept && param.isDept === '1') {
        this.deptId = parseInt(getDeptId())
      }
    }
    this.pageGetDeviceWarn()
  },
  methods: {
    gotoDevice(item) {
      this.$router.push({
        path: '/device/manage/' + item.deviceCore,
        query: { deviceCore: item.deviceCore, deviceName: item.deviceName }
      })
    },
    listDeviceWarnHistory(item) {
      listDeviceWarnHistory({
        warnId: item.warnId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.warnHistoryList = data
          this.showHistory = true
        }
      })
    },
    formatDate(time) {
      if (!time) {
        return formatDate(this, Math.round(new Date().getTime() / 1000))
      }
      return formatDate(this, time)
    },
    formatDeviceWarnStatus(status) {
      if (status === 0) {
        return this.$t('untreated')
      } else if (status === 1) {
        return this.$t('misinformation')
      } else if (status === 2) {
        return this.$t('processed')
      }
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    handleSelectionChange(val) {
      const mList = []
      val.forEach(function(row) {
        mList.push(row.warnId)
      })
      this.mList = mList
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetDeviceWarn()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetDeviceWarn()
    },
    mDel() {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceWarnList({
            idList: that.mList
          }).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetDeviceWarn()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    del(index) {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceWarn({
            warnId: index.warnId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              that.pageGetDeviceWarn()
              successNotice(that)
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    edit(item) {
      this.warn = item
      this.dialogTableVisible = true
    },
    pageGetDeviceWarn() {
      const startDate = Math.round(this.startDate / 1000)
      const endDate = Math.round(this.endDate / 1000)
      pageGetDeviceWarn({
        companyId: this.companyId,
        deptId: this.deptId,
        status: this.status,
        deviceCore: this.deviceCore,
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        startDate: startDate === 0 ? null : startDate,
        endDate: endDate === 0 ? null : endDate
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          this.warnList = data.data
        }
      })
    },
    updateStatus() {
      updateDeviceWarn({
        status: this.warn.status,
        warnId: this.warn.warnId
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
          this.dialogTableVisible = false
        }
        this.pageGetDeviceWarn()
      })
    }
  }
}
</script>
<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.el-table .danger-row {
  background: #ff5d42;
}
</style>
